using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using BlockeyEssentials;

namespace Blockey.GameObjects3D
{
    public class DrawableCustom : DrawableObject
    {
        public DrawableCustom(GraphicsDevice oDevice, Texture2D oTexture, bool oLighting)
        {
            m_oBasicEffect = new BasicEffect(oDevice);
            m_oBasicEffect.TextureEnabled = true;
            SetTransformation(Vector3.Zero, Vector3.Zero, 1);

            if (oLighting)
                m_oBasicEffect.EnableDefaultLighting();

            SetTexture(oTexture);
            SetSphere();
        }

        public void SetVertices(List<VertexPositionNormalTexture> oVPNT)
        {
            m_oVertices = oVPNT.ToArray();
        }

        public override void Draw(GraphicsDevice oGraphics, Camera3D oCamera)
        {
            if (m_oBasicEffect == null)
            {
                return;
            }

            if (m_oVertexBuffer == null && m_oVertices != null)
            {
                m_oVertexBuffer = new VertexBuffer(
                    oGraphics,
                    VertexPositionNormalTexture.VertexDeclaration,
                    m_oVertices.Length,
                    BufferUsage.WriteOnly
                    );
            }

            oCamera.ApplyCameraEffect(ref m_oBasicEffect);

            foreach (EffectPass oPass in m_oBasicEffect.CurrentTechnique.Passes)
            {
                oPass.Apply();

                m_oVertexBuffer.SetData(0, m_oVertices, 0, m_oVertices.Length, 0);
                oGraphics.SetVertexBuffer(m_oVertexBuffer);

                oGraphics.DrawUserPrimitives<VertexPositionNormalTexture>(PrimitiveType.TriangleList, m_oVertices, 0, m_oVertices.Length / 3);
            }

        }

        //protected override void ApplyWorldEffect()
        //{
        //    m_mWorld =
        //        Matrix.CreateScale(m_fScale) *
        //        Matrix.CreateRotationX(m_vRotation.X) *
        //        Matrix.CreateRotationY(m_vRotation.Y) *
        //        Matrix.CreateRotationZ(m_vRotation.Z) *
        //        Matrix.CreateTranslation(m_vTranslation);

        //    m_oBasicEffect.World = m_mWorld;
        //}

        public override void SetTexture(Texture2D oTexture)
        {
            m_oBasicEffect.Texture = oTexture;
            m_oBasicEffect.TextureEnabled = true;
        }

        protected override void SetSphere()
        {
            m_oSphere = new BoundingSphere(base.m_vTranslation, _Radius);
        }

        private VertexPositionNormalTexture[] m_oVertices;
        private VertexBuffer m_oVertexBuffer;
        protected BasicEffect m_oBasicEffect;
        private float _Radius;

    }
}
